import networkx as nx
from create_networks import create_network
from run_iterations  import run_iterations
import random
import numpy as np

def make_random_list(length):
    return [random.randint(1, 10000) for _ in range(length)]

def run_batch(num_runs,
              broker_type,
              model_type_base,
              total_iterations=4000,
              record_interval=25,
              n=25,
              network_type=None,
              seed=None,
              k=None,
              directed=False,
              cluster=None,
              p_in=None,
              p_out=None,
              p=None):
    """
    Runs `run_iterations` num_runs times, creating a fresh network each time.
    - If `seed` is provided, the same seed is reused for all runs.
    - Otherwise, random seeds are drawn for each replicate.
    """
    # 1) Prepare a list of seeds
    if seed is not None:
        seed_list = [seed] * num_runs
    else:
        seed_list = make_random_list(num_runs)

    for idx in range(num_runs):
        # idx is 0-based; run_no is 1-based
        run_no = idx + 1
        this_seed = seed_list[idx]

        # print progress
        print(f"[{run_no}/{num_runs}] seed={this_seed}")

        # 2) build a fresh network for this run
        G = create_network(
            n=n,
            k=k,
            network_type=network_type,
            directed=directed,
            seed=this_seed,
            cluster=cluster,
            p_in=p_in,
            p_out=p_out,
            p=p 
        )

        np.random.seed(this_seed)
        num_nodes = 200
        num_issues = 10
        mean_opinion = 0
        std_dev_opinion = 0.15

        opinions = np.random.normal(mean_opinion, std_dev_opinion, (num_nodes, num_issues))
        opinions[opinions < -1] = -1
        opinions[opinions > 1] = 1

        identity_values = [-1, 1]
        identities = np.random.choice(identity_values, num_nodes) 

        betas = np.clip(np.random.normal(0.5, 0.15, num_nodes), 0, 1)

        alphas = np.clip(np.random.normal(1, 0.3, num_nodes), 0, 2) # tolerance for dissimilarity

        for i in range(num_nodes):
          G.add_node(i, opinions=opinions[i], identity=identities[i], beta = betas[i], alpha = alphas[i])

        # 3) compose this run's model_type (with zero–padded run number)
        model_type = f"{model_type_base}_run{run_no:03d}"

        # 4) simulation and export CSV
        run_iterations(
            G,
            total_iterations=total_iterations,
            record_interval=record_interval,
            broker_type=broker_type,
            model_type=model_type
        )

if __name__ == "__main__":
    run_batch(
        num_runs=10,
        broker_type="baseline",
        model_type_base="er",
        n=200,
        network_type="Gnp",
        k=8,
        p=0.05
    )
